<script setup lang="ts">
import { reactive,onMounted } from 'vue'
import {ArcGisMapServerImageryProvider, Viewer} from "cesium";
import * as Cesium from "cesium";
// import "cesium/Build/Cesium/Widgets/widgets.css";
onMounted(()=>{
  initCesium()
})

function initCesium() {
  Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzZWU2MzMwYS1mYWIwLTQ1NDgtOTdlMy0wZjMzZTA5MTBhYmMiLCJpZCI6MTUyNzkwLCJpYXQiOjE2ODg5ODAwOTV9.P7_-7u976U2uWZvTu1s0WYbkURPsQ7iAn_zpRti4KDI'
  // const viewer = new Viewer("cesiumContainer");
  const arcGis = new Cesium.ArcGisMapServerImageryProvider({
    url:"https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"
  })
  const geoq = new Cesium.UrlTemplateImageryProvider({
    url: 'https://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',
    // tilingScheme: new Cesium.GeographicTilingScheme(),
    maximumLevel: 17,
    defaultAlpha: 0,
  });
  const google=new Cesium.UrlTemplateImageryProvider({
    url:'http://www.google.cn/maps/vt?lyrs=s@800&x={x}&y={y}&z={z}',
    tilingScheme:new Cesium.WebMercatorTilingScheme(),
    minimumLevel:1,
    maximumLevel:20
  });
  const tiandiTu = new Cesium.WebMapTileServiceImageryProvider({
    url: "http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=f69df935f2b4e5d06629d91c56be2809",
    format: "image/png",
    layer: "",
    style: "",
    tileMatrixSetID: "",
  })

  /*设置查看器*/
  const viewer = new Viewer("cesiumContainer",{
    // 需要进行可视化的数据源的集合
    animation: false, // 是否显示动画控件
    shouldAnimate: true,
    homeButton: false, // 是否显示Home按钮
    fullscreenButton: false, // 是否显示全屏按钮
    baseLayerPicker: false,  //是否显示图层选择控件 设置自定义影像时 这个参数要为false，否则不会生效
    geocoder: false, // 是否显示地名查找控件
    timeline: false, // 是否显示时间线控件
    sceneModePicker: false, // 是否显示投影方式控件
    navigationHelpButton: false, // 是否显示帮助信息控件
    infoBox: true, // 是否显示点击要素之后显示的信息
    requestRenderMode: true, // 启用请求渲染模式
    scene3DOnly: false, // 每个几何实例将只能以3D渲染以节省GPU内存
    sceneMode: 3, // 初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
    fullscreenElement: document.body, // 全屏时渲染的HTML元素 暂时没发现用处
    imageryProvider: arcGis, // 加载各种影像图层
    terrainProvider: Cesium.createWorldTerrain({
      requestWaterMask: true, // 请求水体效果所需要的海岸线数据
      requestVertexNormals: true, // 请求地形照明数据
    }),
  });

  /*设置摄像头*/
  // viewer.camera.setView({
  //   // 位置
  //   destination: Cesium.Cartesian3.fromDegrees(113.3189777,23.114115,200),
  //   // 方向、俯视和仰视的视角
  //   orientation: {
  //     heading:Cesium.Math.toRadians(90),
  //     pitch:Cesium.Math.toRadians(-90),
  //   }
  // })

  // Set the initial camera view to look at Manhattan
  const initialPosition = Cesium.Cartesian3.fromDegrees(
      -74.01881302800248,
      40.69114333714821,
      753
  );
  const initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(
      21.27879878293835,
      -21.34390550872461,
      0.0716951918898415
  );
  viewer.scene.camera.setView({
    destination: initialPosition,
    orientation: initialOrientation,
    endTransform: Cesium.Matrix4.IDENTITY,
  });

  // 设置城市模型
  const city = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({url:Cesium.IonResource.fromAssetId(75343)}))

  // 定义3D样式
  const heightStyle = new Cesium.Cesium3DTileStyle({
    color: {
      // 条件判断建筑物的颜色
      conditions: [
        ['${Height} >= 300', 'rgba(45,0,75,0.5)'],
        ["${Height}>=200", "rgb(102,71,151)"],
        ["${Height}>=100", "rgba(170,162,204,0.5)"],
        ["${Height}>=50", "rgb(224,226,238)"],
        ["${Height}>=25", "rgb(252,230,200)"],
        ["${Height}>=10", "rgba(248,176,87,0.5)"],
        ["${Height}>=5", "rgb(198,106,11)"],
        ["true", "rgb(127,59,8)"],
      ],
    },
  })
  // 修改样式
  city.style = heightStyle;

  var geojsonOptions = {
    clampToGround: true
  };
  // 从 GeoJson 文件加载邻域边界
  // Data from : https://data.cityofnewyork.us/City-Government/Neighborhood-Tabulation-Areas/cpf4-rkhq
  var neighborhoodsPromise = Cesium.GeoJsonDataSource.load('/assets/SampleData/sampleNeighborhoods.geojson', geojsonOptions);
  //GeoJSON是一种对各种地理数据结构进行编码的格式，基于Javascript对象表示法
  //(JavaScript Object Notation, 简称JSON)的地理空间信息数据交换格式。
  // GeoJSON对象可以表示几何、特征或者特征集合。
  //GeoJSON支持下面几何类型：点、线、面、多点、多线、多面和几何集合
  // 保存邻域数据的新实体集合
  var neighborhoods;
  neighborhoodsPromise.then(function (dataSource) {
    // 将新数据作为实体添加到查看器
    viewer.dataSources.add(dataSource);
    neighborhoods = dataSource.entities;

    // Get the array of entities
    var neighborhoodEntities = dataSource.entities.values;
    for (var i = 0; i < neighborhoodEntities.length; i++) {
      var entity = neighborhoodEntities[i];

      if (Cesium.defined(entity.polygon)) {
        // Use kml neighborhood value as entity name
        entity.name = entity.properties.neighborhood;
        // Set the polygon material to a random, translucent color
        entity.polygon.material = Cesium.Color.fromRandom({
          red: 0.1,
          maximumGreen: 0.5,
          minimumBlue: 0.5,
          alpha: 0.6
        });
        // 告诉多边形为地形着色。 ClassificationType.CESIUM_3D_TILE 将为 3D 图块集着色，而 ClassificationType.BOTH 将为 3d 图块和地形着色（BOTH 是默认值）
        // Tells the polygon to color the terrain. ClassificationType.CESIUM_3D_TILE will color the 3D tileset, and ClassificationType.BOTH will color both the 3d tiles and terrain (BOTH is the default)
        entity.polygon.classificationType = Cesium.ClassificationType.TERRAIN;
        // 生成多边形中心
        var polyPositions = entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
        // 边界球
        var polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center;
        // 椭球体
        polyCenter = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter);
        entity.position = polyCenter;
        // 生成标签
        entity.label = {
          text: entity.name,
          showBackground: true,
          scale: 0.6,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(10.0, 8000.0),
          disableDepthTestDistance: 100.0
        };
      }
    }
  });

  var kmlOptions = {
    camera: viewer.scene.camera,
    canvas: viewer.scene.canvas,
    // 如果我们想要将几何特征（多边形、线串和线性环）固定在地面上，则为 true。
    clampToGround: true
  };
  //KML文件是谷歌公司创建的一种地标性文件。
  //用于记录某一地点、或连续地点的时间、经度、纬度、海拔等地理信息数据，供GE等有关软件使用。
  // Load geocache points of interest from a KML file
  // Data from : http://catalog.opendata.city/dataset/pediacities-nyc-neighborhoods/resource/91778048-3c58-449c-a3f9-365ed203e914
  var geocachePromise = Cesium.KmlDataSource.load('/assets/SampleData/sampleGeocacheLocations.kml', kmlOptions);

  // 将 geocache 广告牌实体添加到场景中并为其设置样式
  geocachePromise.then(function (dataSource) {
    // 将新数据作为实体添加到查看器
    viewer.dataSources.add(dataSource);

    // 获取实体数组
    var geocacheEntities = dataSource.entities.values;

    for (var i = 0; i < geocacheEntities.length; i++) {
      var entity = geocacheEntities[i];
      if (Cesium.defined(entity.billboard)) {
        // 调整垂直原点，使图钉位于地形上
        entity.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
        entity.billboard.image = '/assets/tagpark.png'
        // 禁用标签以减少混乱
        entity.label = undefined;
        // 添加距离显示条件
        entity.billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(10.0, 20000.0);
        // 以度为单位计算纬度和经度
        var cartographicPosition = Cesium.Cartographic.fromCartesian(entity.position.getValue(Cesium.JulianDate.now()));
        var latitude = Cesium.Math.toDegrees(cartographicPosition.latitude);
        var longitude = Cesium.Math.toDegrees(cartographicPosition.longitude);
        // 修改描述
        var description = '<table class="cesium-infoBox-defaultTable cesium-infoBox-defaultTable-lighter"><tbody>' +
            '<tr><th>' + "Longitude" + '</th><td>' + longitude.toFixed(5) + '</td></tr>' +
            '<tr><th>' + "Latitude" + '</th><td>' + latitude.toFixed(5) + '</td></tr>' +
            '<tr><th>' + "实时人流" + '</th><td>' + Math.floor(Math.random() * 20000) + '</td></tr>' +
            '<tr><th>' + "安全等级" + '</th><td>' + Math.floor(Math.random() * 5) + '</td></tr>' +
            '</tbody></table>';
        entity.description = description;
      }
    }
  });

  // 从czml文件加载飞行路径
  const dronePromise = Cesium.CzmlDataSource.load('/assets/SampleData/sampleFlight.czml');

  // 无人机实体
  let drone;
  dronePromise.then(function (dataSource) {
    viewer.dataSources.add(dataSource);
    drone = dataSource.entities.getById('Aircraft/Aircraft1');
    drone.model = {
      uri:'/assets/SampleData/Models/CesiumDrone.gltf',
      // uri: '/assets/SampleData/Models/ferrari2.gltf',
      minimumPixelSize: 128,
      maximumScale: 1000,
      silhouetteColor: Cesium.Color.WHITE,
      silhouetteSize: 2
    }

    drone.orientation = new Cesium.VelocityOrientationProperty(drone.position);
    drone.viewFrom = new Cesium.Cartesian3(0, -30, 30);
    // 设置动画
    viewer.clock.shouldAnimate = true;
  })
}
</script>

<template>
  <div id="cesiumContainer"/>
</template>

<style scoped>
#cesiumContainer {
  width: 100%;
  /*height: 100%;*/
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>
